package cn.yunbamboos.token;

import cn.yunbamboos.token.event.LoginTokenEvent;
import cn.yunbamboos.token.event.LogoutTokenEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;

public class TokenContainerManager implements ITokenContainerManager {

    private static final Logger logger = LoggerFactory.getLogger(ITokenContainerManager.class);

    private final ITokenContainer tokenContainer;

    public TokenContainerManager(ITokenContainer tokenContainer) {
        this.tokenContainer = tokenContainer;
    }

    /**
     * 登陆添加token
     */
    @Async("TaskExecutor")
    @EventListener
    public void onApplicationEvent(LoginTokenEvent event) {
        String id = event.getId();
        String token = event.getToken();
        tokenContainer.set(id, token);
        logger.info("add token {} {}", id, token);
    }

    /**
     * 注销服务删除token
     */
    @Async("TaskExecutor")
    @EventListener
    public void onApplicationEvent(LogoutTokenEvent event) {
        String id = event.getId();
        tokenContainer.remove(id);
        logger.info("remove token {}", id);
    }


}
